import os
import re
from datetime import datetime

class VersionUpdater:
    def __init__(self):
        self.version_file = "version_history.md"
        self.date = "2025-02-07"
        self.maintainer = "罗森"
        self.load_current_version()

    def load_current_version(self):
        """从版本历史文件中加载当前版本号"""
        if os.path.exists(self.version_file):
            with open(self.version_file, 'r', encoding='utf-8') as f:
                content = f.read()
                # 从主版本号中提取版本信息
                version_match = re.search(r'主版本号：v(\d+)\.(\d+)\.(\d+)', content)
                if version_match:
                    self.major = int(version_match.group(1))
                    self.minor = int(version_match.group(2))
                    self.patch = int(version_match.group(3))
                else:
                    self.major = 1
                    self.minor = 0
                    self.patch = 0

    def update_version(self, change_type='patch'):
        """更新版本号"""
        if change_type == 'major':
            self.major += 1
            self.minor = 0
            self.patch = 0
        elif change_type == 'minor':
            self.minor += 1
            self.patch = 0
        else:  # patch
            self.patch += 1
        
        return self.get_version()

    def get_version(self):
        """获取当前版本号"""
        return f"v{self.major}.{self.minor}.{self.patch}"

    def clean_content(self, content):
        """清理文件内容，删除重复的更新记录"""
        # 分离更新日志部分和其他部分
        log_start = content.find("## 更新日志")
        log_end = content.find("## 自动更新脚本规则")
        
        if log_start == -1 or log_end == -1:
            return content
            
        header = content[:log_start]
        log_section = content[log_start:log_end]
        footer = content[log_end:]
        
        # 清理重复的更新记录
        log_entries = re.findall(r'### v[\d\.]+.*?\n(?:- .*?\n)+', log_section, re.DOTALL)
        unique_entries = []
        seen = set()
        
        for entry in log_entries:
            if entry not in seen:
                seen.add(entry)
                unique_entries.append(entry)
        
        # 重建更新日志部分
        new_log_section = "## 更新日志\n" + "".join(unique_entries)
        
        return header + new_log_section + footer

    def update_file_version(self, file_path):
        """更新文件中的版本信息"""
        if not os.path.exists(file_path):
            return False

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()

            # 清理内容
            content = self.clean_content(content)

            # 更新版本号
            content = re.sub(r'主版本号：v[\d\.]+', f'主版本号：{self.get_version()}', content)
            content = re.sub(r'子版本号：v[\d\.]+', f'子版本号：{self.get_version()}', content)
            content = re.sub(r'版本号：v[\d\.]+', f'版本号：{self.get_version()}', content)
            
            # 更新所有日期字段
            date_pattern = r'\d{4}-\d{2}-\d{2}'
            content = re.sub(f'最后更新：{date_pattern}', f'最后更新：{self.date}', content)
            content = re.sub(f'创建日期：{date_pattern}', f'创建日期：{self.date}', content)
            content = re.sub(f'\({date_pattern}\)', f'({self.date})', content)

            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)

            return True
        except Exception as e:
            print(f"Error updating file {file_path}: {str(e)}")
            return False

    def update_all_files(self, directory):
        """更新指定目录下所有markdown文件的版本信息"""
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith('.md'):
                    file_path = os.path.join(root, file)
                    self.update_file_version(file_path)

    def log_update(self, message):
        """记录更新日志"""
        if os.path.exists(self.version_file):
            with open(self.version_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 检查是否已存在相同的更新记录
            log_entry = f"### {self.get_version()} ({self.date})\n- {message}\n\n"
            if log_entry not in content:
                # 在更新日志部分添加新记录
                insert_pos = content.find("## 更新日志") + len("## 更新日志\n")
                new_content = content[:insert_pos] + log_entry + content[insert_pos:]
                
                # 清理重复记录
                new_content = self.clean_content(new_content)
                
                with open(self.version_file, 'w', encoding='utf-8') as f:
                    f.write(new_content)

def main():
    updater = VersionUpdater()
    
    # 更新版本号
    updater.update_version('patch')
    
    # 更新所有文件
    base_dir = "../../"  # 相对于脚本位置的基础目录
    updater.update_all_files(base_dir)
    
    # 记录更新
    updater.log_update("自动更新版本信息")

if __name__ == "__main__":
    main() 